﻿using System;
using System.Linq;
using System.Windows.Forms;
using AutoplanetaTaskManager.Daos;
using AutoplanetaTaskManager.Daos.EntityFramework;
using AutoplanetaTaskManager.Models;
using AutoplanetaTaskManager.Security;

namespace AutoplanetaTaskManager.Views
{
    public partial class AuthForm : Form
    {
        private MainViewForm _mainForm;
        private readonly IUserDao _userDao = new UserDao();
        private IRoleDao _roleDao = new RoleDao();

        public AuthForm(MainViewForm mainForm)
        {
            InitializeComponent();
            _mainForm = mainForm;

            /*try
            {
                using (AtmDbEntities db = new AtmDbEntities())
                    db.User.FirstOrDefault();
            }
            catch
            {
                DialogResult result =
                   MessageBox.Show("В данный момент база данных не доступна. Подождите некоторое время и попробуйте снова.",
                   "Ошибка подключения!", MessageBoxButtons.OK);
                if (result == DialogResult.OK)
                {
                    _mainForm.Dispose();
                    Dispose();
                }
            }*/
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            _mainForm.Dispose();
            Dispose();
        }

        private void applyButton_Click(object sender, EventArgs e)
        {
            StartAuth();
        }

        private void AuthForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (SecurityManager.Get().User == null)
                _mainForm.Dispose();
        }

        private void AuthForm_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                StartAuth();
        }

        private void userNameTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                StartAuth();
        }

        private void passwordTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                StartAuth();
        }

        private void StartAuth()
        {
            User user = null;
            string userName = userNameTextBox.Text;
            string password = passwordTextBox.Text;

            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
                messageLabel.Text = "Вы должны заполнить все необходимые поля";
            else user = _userDao.Get(userName, password);

            if (user == null)
                messageLabel.Text = "Запись не существует. Проверьте правильность имени/пароля";
            else
            {
                SecurityManager.Get().User = user;
                SecurityManager.Get().Role = _roleDao.Get(user.RoleId);
                _mainForm.SetPostItemsContent();
                _mainForm.Text = string.Format("Менеджер заданий ({0} {1})", user.FirstName, user.LastName);
                Dispose();
            }
        }

        
    }
}
